<template>
	<view class="bgColor">
		<view class="form">
			<text class="title"> 你好，<br />欢迎注册口袋校园 </text>
			<text class="info">未注册的用户请点击快速注册，注册后登录</text>
			<uni-forms label-position="top" ref="form" :modelValue="userForm" :rules="rules">
				<uni-forms-item label="手机号码" name="mobile">
					<input type="text" v-model="userForm.mobile" placeholder="请输入手机号码" />
				</uni-forms-item>
				<uni-forms-item label="密码" name="password">
					<input type="password" v-model="userForm.password" placeholder="请输入密码" />
				</uni-forms-item>
				<uni-forms-item label="验证码" name="code">
					<input type="number" v-model="userForm.code" placeholder="请输入验证码" />
					<button class="captchaBtn" v-if="!timer" @click="radomNum">验证码</button>
					<button class="captchaBtn active" v-else :disabled="timer != 0">{{ CountDown }} 秒</button>
				</uni-forms-item>
				<!-- 同意协议 -->
				<view class="access">
					<checkbox-group @change="changSelect">
						<label class="radio">
							<checkbox :checked="isSelect" />已经阅读并 <span>
								同意用户协议、隐私政策</span>
						</label>
					</checkbox-group>
				</view>
			</uni-forms>
			<button class="btn" :class="{'active': isSelect}" @click="submitForm">注册</button>
			<view class="fun">
				<text @click="gotoLogin">前去登录</text>
			</view>
		</view>

	</view>
</template>

<script setup>
	import {
		reactive,
		ref
	} from "vue"

	// 表单ref引用
	const form = ref(null)

	// 表达数据
	const userForm = reactive({
		mobile: '',
		password: '',
		code: ''
	})
	// 验证码
	let captchaNum = ref('')

	// 规则
	const rules = reactive({
		mobile: {
			// name 字段的校验规则
			rules: [
				// 校验 name 不能为空
				{
					required: true,
					errorMessage: '请填写手机号码',
				},
				{
					validateFunction: function(rule, value, data, callback) {
						// 正则表达式：中国地区的手机号+86
						const passwordPattern = /^1[3-9]\d{9}$/;
						if (!passwordPattern.test(value)) {
							callback('请填写正确手机号码');
						} else {
							callback(); // 验证通过
						}
					}
				}
			],
		},
		password: {
			// name 字段的校验规则
			rules: [
				// 校验 name 不能为空
				{
					required: true,
					errorMessage: '请填写密码',
				},
				{
					validateFunction: function(rule, value, data, callback) {
						// 正则表达式：至少一个字母且长度大于6位
						const passwordPattern = /^(?=.*[a-zA-Z]).{6,}$/;
						if (!passwordPattern.test(value)) {
							callback('密码必须包含至少一个字母且长度大于6位');
						} else {
							callback(); // 验证通过
						}
					}
				}
			],
		},
		code: {
			// name 字段的校验规则
			rules: [
				// 校验 name 不能为空
				{
					required: true,
					errorMessage: '验证码不能为空',
				},
				{
					validateFunction: function(rule, value, data, callback) {
						if (!captchaNum.value) {
							callback("请获取验证码")
						}
						if (value != captchaNum.value) {
							callback("验证码有误")
						}
					}
				}
			],
		}
	})

	// 定时器
	let timer = ref(0)
	let CountDown = ref(60)

	// 协议按钮
	const isSelect = ref(false)

	// 修改协议状态
	function changSelect() {
		isSelect.value = !isSelect.value
	}

	// 生成验证码
	function radomNum() {
		if (!timer.value) {
			// 字符集
			const characters = '0123456789';
			let result = '';
			for (let i = 0; i < 4; i++) {
				const randomIndex = Math.floor(Math.random() * characters.length); // 随机索引
				result += characters[randomIndex]; // 追加随机字符
			}
			// 生成的验证码
			captchaNum.value = result;
			uni.showModal({
				title: "验证码",
				content: '验证码: ' + captchaNum.value,
				showCancel: false
			})
			timer.value = setInterval(() => {
				CountDown.value -= 1;
				// 验证码超时 
				if (CountDown.value <= 0) {
					clearInterval(timer.value)
					CountDown.value = 60
					captchaNum.value = ''
					timer.value = null
				}
			}, 1000)
		}
	}

	// 注册事件
	async function submitForm() {
		try {
			if (!isSelect.value) {
				uni.showToast({
					title: "请勾选协议",
					icon: 'error'
				})
				return
			}

			// 表单验证
			const res = await form.value.validate()
			delete res.code

			// 开启加载框
			uni.showLoading({ title: "注册中..." })

			// 调用注册接口
			const { result } = await uniCloud.callFunction({
				name: "user_add",
				data: res
			})

			// 处理注册结果
			if (result.code === -1) {
				throw new Error(result.mes)
			}

			// 注册成功
			await uni.showToast({
				title: "注册成功",
				icon: 'success',
				duration: 2000
			})

			// 跳转登录页
			uni.reLaunch({ url: "/pages/login/login" })

		} catch (error) {
			uni.showToast({
				title: error.message || "注册失败",
				icon: 'error'
			})
		} finally {
			uni.hideLoading()
		}
	}

	// 跳转到登录页面
	function gotoLogin() {
		uni.reLaunch({
			url: "/"
		})
	}
</script>

<style lang="scss" scoped>
	.bgColor {
		height: 100vh;
		box-sizing: border-box;
		padding: 0 60rpx;
		padding-top: 220rpx;
		position: relative;

		// 表单样式
		.form {
			.title {
				font-size: 56rpx;
				font-weight: bold;
				line-height: 72rpx;
			}

			.info {
				font-size: 20rpx;
				font-weight: 400;
				line-height: 24rpx;
				display: block;
				color: #AAAAAA;
				margin: 8rpx 0;
			}

			.uni-forms {
				margin-top: 90rpx;

				.uni-forms-item::v-deep .uni-forms-item__label span {
					font-size: 36rpx;
					font-weight: bold;
					display: block;
					width: 400rpx;
				}

				.uni-forms-item::v-deep input {
					border-bottom: 1px solid #0000000D;
					height: 96rpx;
					color: #000;
					font-size: 32rpx;
					font-weight: 400;
				}

				.captchaBtn {
					width: 200rpx;
					height: 56rpx;
					position: absolute;
					top: 20rpx;
					right: 10rpx;
					font-size: 30rpx;
					line-height: 56rpx;
					border-radius: 6rpx;
					background-color: #333333;
					color: #fff;
				}

				.captchaBtn.active {
					background-color: #00000066;
				}

				.access {
					margin-top: -10rpx;
				}

				.radio {
					font-size: 20rpx;

					span {
						display: inline-block;
						color: #4B9AFFFF;
						border-bottom-color: #4B9AFFFF;
					}
				}
			}

			.btn {
				margin-top: 80rpx;
				background-color: rgba(0, 0, 0, 0.4);
				border: none;
				color: #fff;
				font-size: 28rpx;
				font-weight: 500;
				height: 96rpx;
				line-height: 96rpx;
			}

			.btn.active {
				background-color: rgba(0, 0, 0);
			}

			.fun {
				margin: 30rpx 0;
				display: flex;
				justify-content: space-between;
				color: #666666;
				font-size: 24rpx;

				text {
					border-bottom: 2rpx solid #666;
				}
			}
		}

	}
</style>